package com.cy.cqb.dockerjava.controller;

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

@Service
public class Shell {
    /**
     * 调用shell，
     * parameter:arg1  arg2 arg3,
     * return  void
     * */
    public void callShell(){
        try {
            Runtime rt = Runtime.getRuntime();
            rt.exec("/home/ubuntu/test/test.sh arg1 arg2 arg3");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 运行shell
     *
     * @param shStr  需要执行的shell绝对路径 和参数
     * @return echo 打印结果保存在list中,shell中echo值放到list中
     * @throws IOException
     */
    public List runShell(String shStr) throws Exception {
        List<String> strList = new ArrayList();

        Process process;
        process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shStr},null,null);
        InputStreamReader ir = new InputStreamReader(process
                .getInputStream());
        LineNumberReader input = new LineNumberReader(ir);
        String line;
        process.waitFor();
        while ((line = input.readLine()) != null){
            strList.add(line);
            System.out.println(line);
        }
        return strList;
    }

}
